package com.yao.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yao.common.enums.SysErrorEnum;
import com.yao.common.exception.BusinessException;
import com.yao.sys.entity.MenuEntity;
import com.yao.sys.entity.dto.MenuDto;
import com.yao.sys.mapper.MenuMapper;
import com.yao.sys.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 菜单表 接口实现
 *
 * @author autoCode
 * @version 1.0.0-SNAPSHOT
 * @date 2019-12-09
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, MenuDto> implements MenuService {

    @Autowired
    private MenuMapper mapper;

    @Override
    // @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, timeout = 1,
    // rollbackFor = BusinessException.class)
    public MenuEntity add(MenuDto entity) {
        LambdaQueryWrapper<MenuDto> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(null != entity.getName(), MenuEntity::getName, entity.getName());

        MenuEntity one = this.getOne(wrapper);

        if (null != one) {
            String errmsg = String.format("不能重复添加菜单 name:%s ", entity.getName());
            throw new BusinessException(SysErrorEnum.ERROR.getErrCode(), "已经存在该[{}]名字的菜单", entity.getName());
        }

        if (!this.save(entity)) {
            throw new BusinessException("新增菜单失败.");
        }

        return null;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, timeout = 1,
        rollbackFor = BusinessException.class)
    public MenuEntity modifyById(MenuDto entity) {
        if (null == entity.getId()) {
            throw new BusinessException("更新的id不存在." + entity);
        }

        this.updateById(entity);

        return entity;
    }

    @Override
    public List<MenuDto> listRoot() {
        return mapper.listRootMenu();
    }

    @Override
    public List<MenuDto> listAllMenu() {

        List<MenuDto> root = mapper.listRootMenu();

        root.forEach(e -> {
            List<MenuDto> child = mapper.listMenuByParentId(e.getId());
            e.setChild(child);
        });

        return root;
    }
}